//对axios的二次封装
import Axios from 'axios'

import nProgress from 'nprogress'

//引入elementui的消息框
import { Message } from 'element-ui'

//引入环境地址
import router from '../router/index'
import envConfig from '../http/env'
const { baseURL } = envConfig.prod

//创建一个Axios实例
const service = Axios.create({
    baseURL: baseURL,
    timeout: 5000
})

//设置请求拦截器
service.interceptors.request.use(config => {
    // console.log('请求拦截', config)
    nProgress.start()
    //如果不是调用登录接口，才携带token向后台发请求
    if (config.url !== '/') {
        const token = sessionStorage.getItem('token')
        config.headers['Authorization'] = token
    }

    return config
}, error => {
    return Promise.reject(error)
})


//响应拦截器
service.interceptors.response.use(res => {
    nProgress.done()
    // console.log('响应拦截器：', res)
    const { data: result, meta: { msg, status } } = res.data
    const successArr = [200, 201, 204]

    if (successArr.includes(status)) {
        // console.log(res);
// 
        if (res.config.url === '/login') {
            // console.log(1);

            sessionStorage.setItem('token', result.token)
        }
        Message({
            message: msg,
            type: 'success'
        })
        return result
    }

    Message({
        message: msg,
        type: 'error'
    })

    if (msg === '无效token') {
        router.push('/')
    }
    return Promise.reject(msg)

}, error => {
    return Promise.reject(error)
})

export default service